/*
* Copyright 2010 Competentum group
*
* Licensed under the GNU General Public License, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.gnu.org/licenses/gpl.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.competentum.data.parser
{
	public class CSVCursor
	{
		private const TAB:String = '\t';
		private const EOL:String = '\n';

		public var position:int = 0;
		private var string:String;
		private var _lastInFile:Boolean = false;
		
		public function CSVCursor(string:String)
		{
			this.string = string;
		}
		
		public function get currentSlice():String
		{
			if (position == nextItemPosition - 1)
			{
				return '';
			}
			return string.substring(position, nextItemPosition - 1);
		}
		
		public function forward(count:int = 1):void
		{
			if (count > 0)
			{
				for (var i:int = 0; i < count; i ++ )
				{
					position = nextItemPosition;
					if (nextItemPosition == int.MAX_VALUE)
					{
						_lastInFile = true;
					}
				}
			}
		}
		
		public function get nextItemPosition():int
		{
			var tab:int = string.indexOf(TAB, position);
			var eol:int = string.indexOf(EOL, position);
			if (tab < 0)
				tab = int.MAX_VALUE;
			if (eol < 0)
				eol = int.MAX_VALUE;
			if (tab == int.MAX_VALUE && eol == int.MAX_VALUE)
			{
				return int.MAX_VALUE;
			}
			return Math.min(tab, eol) + 1;
		}
		
		public function get lastInLine():Boolean
		{
			return string.charAt(nextItemPosition - 1) == EOL;
		}
		
		public function get lastInFile():Boolean
		{
			return _lastInFile;
		}
	}
}